package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"web_api_gin/dao"
	"web_api_gin/service"
)

func checkPermission() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var permName string
		url := ctx.FullPath()
		if url != "" {
			url = string([]byte(url)[1:])
			permName = strings.Replace(url, "/", ".", -1)
		}
		//路由名为空直接跳过
		if permName == "" {
			ctx.Next()
			return
		}
		ctx.Set("permName", permName)
		if permName == "admin.login.account" || permName == "admin.login.logout" {
			//设置路由数据，方便全局调用
			permData, _ := dao.SysPermission.GetPermByName(ctx, permName)
			ctx.Set("permData", permData)
			ctx.Next()
			return
		}
		hasPermission := service.SysUser.AuthorizationHasPermission(ctx, permName)
		if hasPermission == false {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code":    http.StatusUnauthorized,
				"message": "Unauthorized ",
			})
			ctx.Abort()
		}
		ctx.Next()
	}
}
